﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ChatTest
{
    class Program
    {

        static public Chat.Connection CreateNewConnection(String serverAddress, String username)
        {
            Chat.Connection newConnection;

                try
                {
                    newConnection = Chat.Client.Connect(serverAddress, username, null);

                    if (newConnection != null)
                        newConnection.SendMessage(username, "@all", "/join @all");
                }
                catch (Chat.UsernameTakenException)
                {
                    return null;
                }

            return newConnection;
        }

        static void Main(string[] args)
        {
            const int kClientsCount = 100;
            const String serverAddress = "192.168.253.2";
            const int kMessagesPerMinute = 6;
            const int kMessagesCount = 60;
            const int kSleepDuration = kMessagesCount / kMessagesPerMinute * 1000;


            try
            {
                Chat.Connection[] users = new Chat.Connection[kClientsCount];
                for (int i = 0; i < kClientsCount; i++)
                {
                    users[i] = CreateNewConnection(serverAddress, i.ToString());
                    Thread.Sleep(50);
                }

                System.Threading.Tasks.Task[] tasks = new System.Threading.Tasks.Task[kClientsCount];
                for (int task = 0; task < kClientsCount; task++)
                {
                    int lambdaTask = task;
                    tasks[task] = new System.Threading.Tasks.Task(() =>
                    {
                        for (int msgNumber = 0; msgNumber < kMessagesCount; msgNumber++)
                        {
                            int message = lambdaTask * kMessagesCount + msgNumber;
                            users[lambdaTask].SendMessage(lambdaTask.ToString(), "@all", message.ToString());
                            Thread.Sleep(kSleepDuration);
                        }
                    });
                    //Thread.Sleep(100);
                    tasks[task].Start();
                }

                for (int task = 0; task < kClientsCount; task++)
                {
                    tasks[task].Wait();
                }

            }
            catch (Exception e)
            {
                Console.ReadKey();
            }

        }
    }
}
